from datetime import datetime
from app import db
from app.models.supermarket import Supermarket
from sqlalchemy.ext.hybrid import hybrid_property

# 盲盒商品表模型
class BlindBox(db.Model):
    __tablename__ = 'tb_blind_box'
    
    box_id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='盲盒ID(主键)')
    market_id = db.Column(db.BigInteger, db.ForeignKey('tb_supermarket.market_id', ondelete='SET NULL'), comment='所属超市ID')
    name = db.Column(db.String(100), nullable=False, comment='盲盒名称')
    description = db.Column(db.Text, comment='详细描述')
    original_price = db.Column(db.Numeric(10, 2), comment='商品原价(元)')
    discount_price = db.Column(db.Numeric(10, 2), comment='折扣价格(元)')
    discount_rate = db.Column(db.Numeric(3, 2), comment='折扣率(0-1)')
    category = db.Column(db.String(50), comment='商品分类')
    stock = db.Column(db.Integer, default=0, comment='库存数量')
    sales = db.Column(db.Integer, default=0, comment='销售数量')
    carbon_footprint = db.Column(db.String(20), comment='碳足迹减少量')
    weekly_price = db.Column(db.Numeric(10, 2), comment='周特惠价格(元)')
    unique_code = db.Column(db.String(20), comment='唯一编码')
    window_category_alert = db.Column(db.Boolean, default=False, comment='临期商品提醒')
    create_time = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    expiry_date = db.Column(db.Date, comment='过期日期')
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    status = db.Column(db.Integer, default=1, comment='状态:1-上架,0-下架')
    image_url = db.Column(db.String(255), comment='图片URL')
    
    # 关联
    supermarket = db.relationship('Supermarket', back_populates='boxes', foreign_keys=[market_id])
    contents = db.relationship('BoxContent', back_populates='blind_box', lazy='dynamic', cascade='all, delete-orphan')
    reviews = db.relationship('Review', back_populates='blind_box', lazy='dynamic')
    recommendations = db.relationship('Recommendation', back_populates='blind_box', lazy='dynamic', cascade='all, delete-orphan')
    
    @hybrid_property
    def price(self):
        """返回当前价格，优先使用折扣价"""
        return self.discount_price if self.discount_price else self.original_price
        
    @hybrid_property
    def has_discount(self):
        """检查是否有折扣"""
        return self.discount_price is not None and self.discount_price < self.original_price
        
    @hybrid_property
    def discount_percentage(self):
        """计算折扣百分比"""
        if self.has_discount and self.original_price:
            return int((1 - float(self.discount_price) / float(self.original_price)) * 100)
        return 0
    
    def __repr__(self):
        return f'<BlindBox {self.name}>'
    
    def to_dict(self):
        """转换为字典，用于API响应"""
        return {
            'box_id': self.box_id,
            'market_id': self.market_id,
            'name': self.name,
            'description': self.description,
            'original_price': float(self.original_price) if self.original_price else None,
            'discount_price': float(self.discount_price) if self.discount_price else None,
            'discount_rate': float(self.discount_rate) if self.discount_rate else None,
            'category': self.category,
            'stock': self.stock,
            'sales': self.sales,
            'carbon_footprint': self.carbon_footprint,
            'weekly_price': float(self.weekly_price) if self.weekly_price else None,
            'status': self.status,
            'image_url': self.image_url,
            'supermarket': self.supermarket.name if self.supermarket else None,
            'expiry_date': self.expiry_date.strftime('%Y-%m-%d') if self.expiry_date else None
        }

# 商品基础信息模型
class Product(db.Model):
    __tablename__ = 'tb_product'
    
    product_id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='商品ID(主键)')
    name = db.Column(db.String(100), nullable=False, comment='商品名称')
    category = db.Column(db.String(50), comment='商品分类')
    brand = db.Column(db.String(50), comment='品牌')
    weight = db.Column(db.String(20), comment='重量/规格')
    expiry_date = db.Column(db.Date, comment='过期日期')
    original_price = db.Column(db.Numeric(10, 2), comment='原价(元)')
    image_url = db.Column(db.String(255), comment='图片URL')
    create_time = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联 - 使用back_populates
    box_contents = db.relationship('BoxContent', back_populates='product', lazy='dynamic')
    
    def __repr__(self):
        return f'<Product {self.name}>'

# 盲盒内容模型
class BoxContent(db.Model):
    __tablename__ = 'tb_box_content'
    
    content_id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='内容ID(主键)')
    box_id = db.Column(db.BigInteger, db.ForeignKey('tb_blind_box.box_id', ondelete='CASCADE'), nullable=False, comment='盲盒ID')
    product_id = db.Column(db.BigInteger, db.ForeignKey('tb_product.product_id', ondelete='CASCADE'), nullable=False, comment='商品ID')
    quantity = db.Column(db.Integer, default=1, comment='商品数量')
    create_time = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    
    # 关联关系 - 使用back_populates
    blind_box = db.relationship('BlindBox', back_populates='contents')
    product = db.relationship('Product', back_populates='box_contents')
    
    def __repr__(self):
        return f'<BoxContent {self.content_id}>'

# 评价模型
class Review(db.Model):
    __tablename__ = 'tb_review'
    
    review_id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='评价ID(主键)')
    user_id = db.Column(db.BigInteger, db.ForeignKey('tb_user.user_id', ondelete='SET NULL'), comment='用户ID')
    box_id = db.Column(db.BigInteger, db.ForeignKey('tb_blind_box.box_id', ondelete='SET NULL'), comment='盲盒ID')
    order_id = db.Column(db.BigInteger, comment='订单ID')
    star_rating = db.Column(db.Integer, default=5, comment='星级评分(1-5)')
    content = db.Column(db.Text, comment='评价内容')
    images = db.Column(db.String(1000), comment='图片URL列表(JSON格式)')
    like_count = db.Column(db.Integer, default=0, comment='点赞数')
    is_anonymous = db.Column(db.Boolean, default=False, comment='是否匿名(0-否,1-是)')
    create_time = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    
    # 关联 - 使用back_populates
    user = db.relationship('User', back_populates='reviews')
    blind_box = db.relationship('BlindBox', back_populates='reviews')
    
    def __repr__(self):
        return f'<Review {self.review_id}>'

# 推荐模型
class Recommendation(db.Model):
    __tablename__ = 'tb_recommendation'
    
    recommendation_id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='推荐ID(主键)')
    box_id = db.Column(db.BigInteger, db.ForeignKey('tb_blind_box.box_id', ondelete='CASCADE'), nullable=False, comment='盲盒ID')
    position = db.Column(db.String(50), nullable=False, comment='推荐位置(home_featured/category_top等)')
    sort_order = db.Column(db.Integer, default=0, comment='排序顺序')
    start_time = db.Column(db.DateTime, comment='开始时间')
    end_time = db.Column(db.DateTime, comment='结束时间')
    create_time = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系 - 使用back_populates
    blind_box = db.relationship('BlindBox', back_populates='recommendations')
    
    def __repr__(self):
        return f'<Recommendation {self.recommendation_id}>' 